package com.tql.kingdee.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.reflect.TypeToken;
import com.ruoyi.common.core.utils.StringUtils;
import com.tql.kingdee.request.BaseRequest;
import com.tql.kingdee.request.KingdeeRequest;
import com.tql.kingdee.util.CommonUtil;
import com.tql.kingdee.util.OkhttpUtil;
import com.tql.kingdee.request.LoginReqeust;
import com.tql.kingdee.response.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

public class KingdeeServiceApi {

    private static final String   acctID= "658438f3f35830";
    private static final String  appid= "267103_0d5MXwFvyPhfxe8u3c5o7Z+s7Kwc3rqs";
    private static final String  appsecret="25c2f84666ab4945898a2481d940bc86";
    private static final String   username= "Administrator";
    private static final int        lcid=2052;
    private static final String loginUrl="http://117.71.59.251/k3cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.LoginByAppSecret.common.kdsvc";
    private static final String queryUrl="http://117.71.59.251/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BillQuery.common.kdsvc";

    protected static final Logger logger = LoggerFactory.getLogger(KingdeeServiceApi.class);


    //0.登录金蝶云账号
    /**
     * url:http://117.71.59.251/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BillQuery.common.kdsvc
     * type:POST
     * request:
     body:
     {
     "acctID": "658438f3f35830",
     "appid": "267103_0d5MXwFvyPhfxe8u3c5o7Z+s7Kwc3rqs",
     "appsecret": "25c2f84666ab4945898a2481d940bc86",
     "username": "Administrator",
     "lcid": 2052
     }
     * response:

     {
     "Message": null,
     "MessageCode": null,
     "LoginResultType": 1,
     "Context": {
     "UserLocale": "zh-CN",
     "LogLocale": "zh-CN",
     "DBid": "658438f3f35830",
     "DatabaseType": 3,
     "SessionId": "mxycpsocspniqp5kqtdeyrhe",
     "UseLanguages": [
     {
     "LocaleId": 2052,
     "LocaleName": "中文(简体)",
     "Alias": "CN",
     "LicenseType": 0
     }
     ],
     "UserId": 16394,
     "UserName": "Administrator",
     "CustomName": "同庆楼餐饮股份有限公司",
     "DisplayVersion": "8.2.775.7",
     "DataCenterName": "同庆楼正式环境",
     "UserToken": "7205ee65-7561-4ad3-800f-7b964645d129",
     "CurrentOrganizationInfo": {
     "ID": 1,
     "AcctOrgType": "1",
     "Name": "同庆楼集团",
     "FunctionIds": [
     101,
     102,
     103,
     104,
     108,
     106,
     107,
     109,
     110,
     111,
     112,
     113,
     114
     ]
     },
     "IsCH_ZH_AutoTrans": false,
     "ClientType": 32,
     "WeiboAuthInfo": {
     "WeiboUrl": null,
     "NetWorkID": null,
     "CompanyNetworkID": null,
     "Account": null,
     "AppKey": "FkdTqJiNeCQC0ugp",
     "AppSecret": "yCP3ucK2IQUm2D3heHxiarq1RJZwfcnKullRSMOIEM",
     "TokenKey": null,
     "TokenSecret": null,
     "Verify": null,
     "CallbackUrl": null,
     "UserId": null,
     "Charset": {
     "BodyName": "utf-8",
     "EncodingName": "Unicode (UTF-8)",
     "HeaderName": "utf-8",
     "WebName": "utf-8",
     "WindowsCodePage": 1200,
     "IsBrowserDisplay": true,
     "IsBrowserSave": true,
     "IsMailNewsDisplay": true,
     "IsMailNewsSave": true,
     "IsSingleByte": false,
     "EncoderFallback": {
     "DefaultString": "�",
     "MaxCharCount": 1
     },
     "DecoderFallback": {
     "DefaultString": "�",
     "MaxCharCount": 1
     },
     "IsReadOnly": true,
     "CodePage": 65001
     }
     },
     "UTimeZone": {
     "OffsetTicks": 288000000000,
     "StandardName": "(UTC+08:00)北京，重庆，香港特别行政区，乌鲁木齐",
     "Id": 230,
     "Number": "1078_SYS",
     "CanBeUsed": true
     },
     "STimeZone": {
     "OffsetTicks": 288000000000,
     "StandardName": "(UTC+08:00)北京，重庆，香港特别行政区，乌鲁木齐",
     "Id": 230,
     "Number": "1078_SYS",
     "CanBeUsed": true
     },
     "GDCID": "72599d46-8a5c-4219-8111-850083afea2e",
     "Gsid": "ccb9f04d322444ad964",
     "TRLevel": 1,
     "ProductEdition": 0,
     "DataCenterNumber": "100",
     "ContextResultType": 0,
     "TenantId": "",
     "IsDeployAsPublicCloud": false
     },
     "KDSVCSessionId": "e12f0459-e8e5-4620-a119-4406553d9df5",
     "FormId": null,
     "RedirectFormParam": null,
     "FormInputObject": null,
     "ErrorStackTrace": null,
     "Lcid": 0,
     "AccessToken": null,
     "CustomParam": {
     "FChkGUIOldMainConsle": false,
     "FChkEnabledSeqReq": false,
     "FIsDisabledGridRowCopy": false,
     "FIsDisabledCellSection": false,
     "FFieldDisabledShowBorder": false,
     "FListQuickFilterBackOld": false,
     "FImgFileCompress": false,
     "FSystemTipsRule": "",
     "FUnAllowTableColumnAutoHidden": false,
     "GlobalWatermarkConfigStr": "eyJ3aWR0aCI6MzAwLCJoZWlnaHQiOjE2MCwiYW5nbGUiOi0xNSwid2F0ZXJtYXJrdGV4dCI6IiAiLCJsaWN0ZXh0IjoiIiwib3BhY2l0eSI6MC4xLCJmb250ZmFtaWx5IjoiTWljcm9zb2Z0IFlhSGVpIiwiZm9udHNpemUiOjE0LCJiaWdfZm9udHNpemUiOjE2LCJzaG93dHlwZSI6MH0="
     },
     "KdAccessResult": null,
     "IsSuccessByAPI": true
     }
***/
    public static String  logonKingdeeK3Cloud()
    {
        LoginReqeust reqeust=new LoginReqeust(acctID,appid,appsecret,username,lcid);
        Gson gson = new Gson();
        String jsonString = gson.toJson(reqeust);
        System.out.println(jsonString);
        String response= OkhttpUtil.post(loginUrl,jsonString,null);
        System.out.println(response);
        LoginResponse loginResponse= gson.fromJson(response, LoginResponse.class);
        String sessionId=null;
        if(null!=loginResponse&&loginResponse.getIsSuccessByAPI().equals(true))
        {
             sessionId=loginResponse.getKDSVCSessionId();
        }
        System.out.println(loginResponse.toString());

        return sessionId;
    }




























    //1.获取金蝶组织架构-相当于同庆楼的门店相关内容
    /**
     * url:http://117.71.59.251/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BillQuery.common.kdsvc
     * type:POST
     * request:

     headers: kdservice-sessionid  参数 -session对话
     body:
      {
          "parameters": [
             {
                 "FormId": "ORG_Organizations",
                  "FieldKeys": "fnumber,fname",
                  "FilterString": "FDocumentStatus='C'",
                 "StartRow": 0,
                  "Limit": 100
              }
          ]
      }
     * response:
     [{"fnumber":"100","fname":"同庆楼集团"},
     "fnumber":"BU101002","fname":"合肥市百弘商贸有限公司"},

     {"fnumber":"BU1010110009","fname":"都汇华府店"},{"fnumber":"BU1010110010","fname":"同庆大包总部"}]
     */

    public static CommonResponse<List<OrgResponse>> getKingdeeOrgBean(String session, String approveDate)
    {
        CommonResponse<List<OrgResponse>> commonResponse=new CommonResponse();
        StringBuffer filterString =new StringBuffer("FDocumentStatus='C'");
        if(StringUtils.isNotEmpty(approveDate))
            filterString.append(" and FAUDITDATE>'"+approveDate+"'");
//        if(StringUtils.isNotEmpty(pFnumber))
//        filterString.append("and FParentID.fnumber like '"+pFnumber+"%'");
        System.out.println("filterString---->"+filterString);
        KingdeeRequest reqeust=new KingdeeRequest("ORG_Organizations","fnumber,fname,FParentID.fnumber as parentFnumber,FParentID.fname as parentFname",filterString.toString(),0,1000);
        List<KingdeeRequest> parameters=new ArrayList<>();
        parameters.add(reqeust);
        BaseRequest baseRequest=new BaseRequest(parameters);
        Gson gson = new Gson();
        String jsonString = gson.toJson(baseRequest);
        System.out.println(jsonString);
        HashMap<String,String> map=new HashMap<>();
        map.put("kdservice-sessionid",session);
        String response= OkhttpUtil.post(queryUrl,jsonString,map);
        System.out.println("response------>"+response);
        if(response.contains("ErrorCode"))
        {
            ErrorInfo errorInfo=  getErrorInfo(response,"getKingdeeOrgBean--approveDate--"+approveDate);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else if(response.contains("response_error"))
        {
            ErrorInfo errorInfo=  new ErrorInfo(1,"10001","getKingdeeOrgBean--approveDate--"+approveDate+"--response---"+response);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else
        {
            List<OrgResponse> orgs = gson.fromJson(response, new TypeToken<List<OrgResponse>>(){}.getType());
            commonResponse.setFlag(0);
            commonResponse.setData(orgs);
        }

            return commonResponse;

    }

    public static ErrorInfo getErrorInfo(String response,String defualtErrMsg) {
        JSONObject jo= (JSONObject) JSONObject.parse(response);
        if(null==jo || jo.isEmpty()) return new ErrorInfo(1,"1000",defualtErrMsg);
        JSONObject Result= (JSONObject) jo.get("Result");
        if(null==Result || Result.isEmpty()) return new ErrorInfo(1,"1000",defualtErrMsg);
        JSONObject ResponseStatus= (JSONObject) Result.get("ResponseStatus");
        if(null==ResponseStatus || ResponseStatus.isEmpty()) return new ErrorInfo(1,"1000",defualtErrMsg);
        Integer ErrorCode= (Integer) ResponseStatus.get("ErrorCode");
        JSONArray Errors= (JSONArray) ResponseStatus.get("Errors");
        if(null==Errors || Errors.isEmpty()) return new ErrorInfo(1,"1000",defualtErrMsg);
        JSONObject JO= (JSONObject) Errors.get(0);
        String msg= JO.getString("Message");
        return  new ErrorInfo(1,ErrorCode+"",msg);
    }

    public static CommonResponse<List<OrgResponse>> postQueryKingdeeDeptForShop(String session, String deptParentCode) {
        CommonResponse<List<OrgResponse>> commonResponse=new CommonResponse();
        StringBuffer filterString =new StringBuffer("FDocumentStatus='C' and  FAUDITDATE>'2020-01-01'");
        if(StringUtils.isNotEmpty(deptParentCode))
            filterString.append(" and FParentID.fnumber like'"+deptParentCode+"%'");


        System.out.println("filterString---->"+filterString);
        KingdeeRequest reqeust=new KingdeeRequest("BD_Department","fnumber,fname,FParentID.fnumber as parentFnumber,FParentID.fname as parentFname",filterString.toString(),0,1000);
        List<KingdeeRequest> parameters=new ArrayList<>();
        parameters.add(reqeust);
        BaseRequest baseRequest=new BaseRequest(parameters);
        Gson gson = new Gson();
        String jsonString = gson.toJson(baseRequest);
        System.out.println(jsonString);
        HashMap<String,String> map=new HashMap<>();
        map.put("kdservice-sessionid",session);
        String response= OkhttpUtil.post(queryUrl,jsonString,map);
        System.out.println("response------>"+response);
        if(response.contains("ErrorCode"))
        {
            ErrorInfo errorInfo=  getErrorInfo(response,"postQueryKingdeeDeptForShop--deptParentCode--"+deptParentCode);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else if(response.contains("response_error"))
        {
            ErrorInfo errorInfo=  new ErrorInfo(1,"10001","postQueryKingdeeDeptForShop--deptParentCode--"+deptParentCode+"--response---"+response);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else
        {
            List<OrgResponse> orgs = gson.fromJson(response, new TypeToken<List<OrgResponse>>(){}.getType());
            commonResponse.setFlag(0);
            commonResponse.setData(orgs);
        }

        return commonResponse;
    }

    public static CommonResponse<List<OrgResponse>> postQueryKingdeeDept(String session, String deptParentCode,String approveDate) {
        CommonResponse<List<OrgResponse>> commonResponse=new CommonResponse();
        StringBuffer filterString =new StringBuffer("FDocumentStatus='C'");
        if(StringUtils.isNotEmpty(deptParentCode))
            filterString.append(" and FParentID.fnumber like'"+deptParentCode+"%'");
        if(StringUtils.isNotEmpty(approveDate))
            filterString.append(" and FAUDITDATE>'"+approveDate+"'");

        System.out.println("filterString---->"+filterString);
        KingdeeRequest reqeust=new KingdeeRequest("BD_Department","fnumber,fname,FParentID.fnumber as parentFnumber,FParentID.fname as parentFname",filterString.toString(),0,1000);
        List<KingdeeRequest> parameters=new ArrayList<>();
        parameters.add(reqeust);
        BaseRequest baseRequest=new BaseRequest(parameters);
        Gson gson = new Gson();
        String jsonString = gson.toJson(baseRequest);
        System.out.println(jsonString);
        HashMap<String,String> map=new HashMap<>();
        map.put("kdservice-sessionid",session);
        String response= OkhttpUtil.post(queryUrl,jsonString,map);
        System.out.println("response------>"+response);
        if(response.contains("ErrorCode"))
        {
            ErrorInfo errorInfo=  getErrorInfo(response,"postQueryKingdeeDept--approveDate--"+approveDate);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else if(response.contains("response_error"))
        {
            ErrorInfo errorInfo=  new ErrorInfo(1,"10001","postQueryKingdeeDept--approveDate--"+approveDate+"--response---"+response);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else
        {
            List<OrgResponse> orgs = gson.fromJson(response, new TypeToken<List<OrgResponse>>(){}.getType());
            commonResponse.setFlag(0);
            commonResponse.setData(orgs);
        }

        return commonResponse;
    }


    /**
     * 查询物料
     * request body
     * {
     *     "parameters": [
     *         {
     *             "FormId": "BD_MATERIAL",
     *             "FieldKeys": "FMATERIALID,fnumber,fname,FSpecification,FBaseUnitId.FNumber as FBaseUnitIdFNumber,FBaseUnitId.FName,FMnemonicCode,FMaterialGroup.fnumber,FMaterialGroup.fname,FApproveDate",
     *             "FilterString": "FDocumentStatus='C' and FApproveDate>'2024-01-01'",
     *             "StartRow": 0,
     *             "Limit": 100
     *         }
     *     ]
     * }
     * @param session
     * @param approveDate
     *
     * @return
     */

    public static CommonResponse<List<MaterialResponse>> postQueryKingdeeMaterial(String session, String approveDate,String stapCode) {
        CommonResponse<List<MaterialResponse>> commonResponse=new CommonResponse();
        StringBuffer filterString =new StringBuffer("FDocumentStatus='C'");
        if(StringUtils.isNotEmpty(approveDate))
            filterString.append(" and FApproveDate>'"+approveDate+"'");
        if(StringUtils.isNotEmpty(stapCode))
            filterString.append(" and fnumber ='"+stapCode+"'");
        System.out.println("filterString---->"+filterString);
        KingdeeRequest reqeust=new KingdeeRequest("BD_MATERIAL","FMATERIALID,fnumber,fname,FSpecification,FBaseUnitId.FNumber as FBaseUnitIdFNumber,FBaseUnitId.FName as FBaseUnitIdFName,FMnemonicCode,FMaterialGroup.fnumber as FMaterialGroupfnumber,FMaterialGroup.fname as FMaterialGroupfname,FApproveDate",filterString.toString(),0,1000);
        List<KingdeeRequest> parameters=new ArrayList<>();
        parameters.add(reqeust);
        BaseRequest baseRequest=new BaseRequest(parameters);
        Gson gson = new Gson();
        String jsonString = gson.toJson(baseRequest);
        System.out.println(jsonString);
        HashMap<String,String> map=new HashMap<>();
        map.put("kdservice-sessionid",session);
        String response= OkhttpUtil.post(queryUrl,jsonString,map);
        System.out.println("response------>"+response);
        if(response.contains("ErrorCode"))
        {
            ErrorInfo errorInfo=  getErrorInfo(response,"postQueryKingdeeMaterial--approveDate--"+approveDate);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else if(response.contains("response_error"))
        {
            ErrorInfo errorInfo=  new ErrorInfo(1,"10001","postQueryKingdeeMaterial--approveDate--"+approveDate+"--response---"+response);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else
        {
            List<MaterialResponse> orgs = gson.fromJson(response, new TypeToken<List<MaterialResponse>>(){}.getType());
            commonResponse.setFlag(0);
            commonResponse.setData(orgs);
        }

        return commonResponse;



    }

    /**
     * 查询单位换算信息
     * {
     *    "parameters": [{
     *         "FormId": "BD_MATERIALUNITCONVERT",
     *         "FieldKeys": "FMaterialId.fnumber,FMaterialId.fname,FConvertDenominator,FCurrentUnitId.FNumber as FCurrentUnitIdFNumber,FCurrentUnitId.FName as FCurrentUnitIdFName,FConvertNumerator,FDestUnitId.fnumber as FDestUnitIdfnumber,FDestUnitId.fname as FDestUnitIdfname ,FMaterialId.Fspecification as FMaterialIdFspecification",
     *         "FilterString": "FDocumentStatus='C' and FApproveDate>'2024-01-01'",
     *         "StartRow": 0,
     *         "Limit": 2000
     *     }]
     * }
     * @param session
     * @param approveDate
     * @param rowNum
     * @return
     */
    public static CommonResponse<List<MaterialTransUnitResponse>> postQueryKingdeeMaterialTransUnit(String session, String approveDate,int rowNum) {
        CommonResponse<List<MaterialTransUnitResponse>> commonResponse=new CommonResponse();
        StringBuffer filterString =new StringBuffer("FDocumentStatus='C'");
        if(StringUtils.isNotEmpty(approveDate))
            filterString.append(" and FApproveDate>'"+approveDate+"'");

        System.out.println("filterString---->"+filterString);
        KingdeeRequest reqeust=new KingdeeRequest("BD_MATERIALUNITCONVERT",
                "FMaterialId.fnumber as FMaterialIdfnumber ,FMaterialId.fname as FMaterialIdfname,FConvertDenominator,FCurrentUnitId.FNumber as FCurrentUnitIdFNumber,FCurrentUnitId.FName as FCurrentUnitIdFName,FConvertNumerator,FDestUnitId.fnumber as FDestUnitIdfnumber,FDestUnitId.fname as FDestUnitIdfname ,FMaterialId.Fspecification as FMaterialIdFspecification",filterString.toString(),rowNum,1000);
        List<KingdeeRequest> parameters=new ArrayList<>();
        parameters.add(reqeust);
        BaseRequest baseRequest=new BaseRequest(parameters);
        Gson gson = new Gson();
        String jsonString = gson.toJson(baseRequest);
        System.out.println(jsonString);
        HashMap<String,String> map=new HashMap<>();
        map.put("kdservice-sessionid",session);
        String response= OkhttpUtil.post(queryUrl,jsonString,map);
        System.out.println("response------>"+response);
        if(response.contains("ErrorCode"))
        {
            ErrorInfo errorInfo=  getErrorInfo(response,"postQueryKingdeeMaterialTransUnit--approveDate--"+approveDate);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else if(response.contains("response_error"))
        {
            ErrorInfo errorInfo=  new ErrorInfo(1,"10001","postQueryKingdeeMaterialTransUnit--approveDate--"+approveDate+"--response---"+response);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else
        {
            List<MaterialTransUnitResponse> orgs = gson.fromJson(response, new TypeToken<List<MaterialTransUnitResponse>>(){}.getType());
            commonResponse.setFlag(0);
            commonResponse.setData(orgs);
        }

        return commonResponse;




    }

    /**
     1.门店采购入库单--集团供应链集采的单据
     * request body
     {
     "parameters": [
     {
     "FormId": "STK_InStock",
     "FieldKeys": "fbillno,FMaterialId.fnumber as FMaterialIdfnumber,FMaterialId.fname as FMaterialIdfname,FLot,FMustQty,FRealQty,FUnitID,FExtAuxUnitId,FMaterialDesc,FExtAuxUnitQty,FMaterialId.Fspecification,FTaxPrice,FAllAmount,FPrice,FAmount,FPriceUnitID.fnumber as FPriceUnitIDfnumber,FPriceUnitID.fname as FPriceUnitIDfname,FPriceUnitQty,FRemainInStockUnitId.fnumber as FRemainInStockUnitIdfnumber,FRemainInStockUnitId.fname as FRemainInStockUnitIdfname,FRemainInStockQty,FDate,FStockOrgId.fnumber as FStockOrgIdfnumber,FStockOrgId.fname as FStockOrgIdfname,FStockDeptId.fnumber as FStockDeptIdfnumber,FStockDeptId.fname as FStockDeptIdfname,FStockId.fnumber as FStockIdfnumber,FStockId.fname as FStockIdfname",
     "FilterString": "FDocumentStatus='C' and FApproveDate>'2024-01-01'",
     "StartRow": 0,
     "Limit": 100
     }
     ]
     }
     * @param session 登录金蝶云账户 的session
     * @param approveDate 审核时间
     * @param rowNum 从第几行开始
     * @return
     *

    数据库表 tql-year2024   tql_material_incase1
    FDID 是单据详情的主键唯一键  对应的表里设置成唯一键
    FDocumentStatus='C' 表示审核通过的单据
    FApproveDate>'2024-01-15'  表示审核时间
    FMaterialId.fnumber LIKE '1%' 表示物料是原材料
    FStockDeptId.fnumber is not null 必须填写具体是哪个工作组收料了
    FStockOrgId.fnumber in('BU1010010024') 那些门店开通服务了
     *
     *
     */
    public static CommonResponse<List<MaterialIncaseResponse>> postQueryKingdeeMaterialIncase(String session, String approveDate, int rowNum,List<String>  depts) {

        CommonResponse<List<MaterialIncaseResponse>> commonResponse=new CommonResponse();
        StringBuffer filterString =new StringBuffer("FDocumentStatus='C' AND FStockDeptId.fnumber is not null ");
        if(StringUtils.isNotEmpty(approveDate))
            filterString.append(" and FApproveDate>'"+approveDate+"'");
        if(!CollectionUtils.isEmpty(depts))
            filterString.append(" and FStockOrgId.fnumber in("+ CommonUtil.getStringDepts1(depts)+")");
        System.out.println("filterString---->"+filterString);
        String queryFields= "FID,FInStockEntry_FEntryId as FDID,fbillno,FMaterialId.fnumber as FMaterialIdfnumber,FMaterialId.fname as FMaterialIdfname,FLot,FMustQty,FRealQty,FUnitID,FExtAuxUnitId,FMaterialDesc,FExtAuxUnitQty,FMaterialId.Fspecification,FTaxPrice,FAllAmount,FPrice,FAmount,FPriceUnitID.fnumber as FPriceUnitIDfnumber,FPriceUnitID.fname as FPriceUnitIDfname,FPriceUnitQty,FRemainInStockUnitId.fnumber as FRemainInStockUnitIdfnumber,FRemainInStockUnitId.fname as FRemainInStockUnitIdfname,FRemainInStockQty,FDate,FStockOrgId.fnumber as FStockOrgIdfnumber,FStockOrgId.fname as FStockOrgIdfname,FStockDeptId.fnumber as FStockDeptIdfnumber,FStockDeptId.fname as FStockDeptIdfname,FStockId.fnumber as FStockIdfnumber,FStockId.fname as FStockIdfname,FApproveDate";
        KingdeeRequest reqeust=new KingdeeRequest("STK_InStock",queryFields  ,filterString.toString(),rowNum,1000);
        List<KingdeeRequest> parameters=new ArrayList<>();
        parameters.add(reqeust);
        BaseRequest baseRequest=new BaseRequest(parameters);
        Gson gson = new Gson();
        String jsonString = gson.toJson(baseRequest);
        System.out.println(jsonString);
        HashMap<String,String> map=new HashMap<>();
        map.put("kdservice-sessionid",session);
        String response= OkhttpUtil.post(queryUrl,jsonString,map);
        System.out.println("response------>"+response);
        if(response.contains("ErrorCode"))
        {
            ErrorInfo errorInfo=  getErrorInfo(response,"postQueryKingdeeMaterialIncase--approveDate--"+approveDate);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else if(response.contains("response_error"))
        {
            ErrorInfo errorInfo=  new ErrorInfo(1,"10001","postQueryKingdeeMaterialIncase--approveDate--"+approveDate+"--response---"+response);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else
        {
            List<MaterialIncaseResponse> orgs = gson.fromJson(response, new TypeToken<List<MaterialIncaseResponse>>(){}.getType());
            commonResponse.setFlag(0);
            commonResponse.setData(orgs);
        }

        return commonResponse;

    }










    /**
     * 2.门店收货单 门店自行采购的物料
     * @param session
     * @param approveDate
     * @param rowNum
     * @param depts
     * @return
     *
     *
     * requestBody
     * {
     *     "parameters": [
     *         {
     *             "FormId": "DE_SCMS_ALLOTRECEIPT",
     *             "FieldKeys": "FID,FEntity_FEntryId as FDID,fbillno,FMaterialId.fnumber as FMaterialIdfnumber,FMaterialId.fname as FMaterialIdfname,FLot,FMustQty,FRealQty,FUnitID,FExtAuxUnitId,FExtAuxUnitQty,FMaterialId.Fspecification,FTaxPrice,FAllAmount,FPrice,FRealAmount,FPriceUnitID.fnumber as FPriceUnitIDfnumber,FPriceUnitID.fname as FPriceUnitIDfname,FPriceUnitQty,FDate,FStockOrgId.fnumber as FStockOrgIdfnumber,FStockOrgId.fname as FStockOrgIdfname,FStockDeptId.fnumber as FStockDeptIdfnumber,FStockDeptId.fname as FStockDeptIdfname,FStockId.fnumber as FStockIdfnumber,FStockId.fname as FStockIdfname",
     *             "FilterString": "FDocumentStatus='C'  AND FMaterialId.fnumber LIKE '1%' AND FStockDeptId.fnumber is not null  and FApproveDate>'2024-01-13' and FStockOrgId.fnumber in('BU1010010013')",
     *             "StartRow": 0,
     *             "Limit": 100
     *         }
     *     ]
     * }
     */
    public static CommonResponse<List<MaterialPurchaseResponse>> postQueryKingdeeMaterialPurchase(String session, String approveDate, int rowNum,List<String> depts) {
        CommonResponse<List<MaterialPurchaseResponse>> commonResponse=new CommonResponse();
        StringBuffer filterString =new StringBuffer("FDocumentStatus='C'  AND FStockDeptId.fnumber is not null");
        if(StringUtils.isNotEmpty(approveDate)) {
//            filterString.append(" and FApproveDate>'"+approveDate+"'");
            //获取当前日期和本月的最后一天
            LocalDate today = LocalDate.parse(approveDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDate lastDay = today.with(TemporalAdjusters.lastDayOfMonth());
            filterString.append(" and FDate>='"+approveDate+"'and FDate<='"+lastDay+"' ");
        }
        if(!CollectionUtils.isEmpty(depts))
            filterString.append(" and FStockOrgId.fnumber in("+ CommonUtil.getStringDepts1(depts)+")");
        System.out.println("filterString---->"+filterString);
        logger.info("filterString---->{}",filterString);
        String fieldKeys="FID,FEntity_FEntryId as FDID,fbillno,FMaterialId.fnumber as FMaterialIdfnumber,FMaterialId.fname as FMaterialIdfname,FLot,FMustQty,FRealQty,FUnitID,FExtAuxUnitId,FExtAuxUnitQty,FMaterialId.Fspecification,FTaxPrice,FAllAmount,FPrice,FRealAmount,FPriceUnitID.fnumber as FPriceUnitIDfnumber,FPriceUnitID.fname as FPriceUnitIDfname,FPriceUnitQty,FDate,FStockOrgId.fnumber as FStockOrgIdfnumber,FStockOrgId.fname as FStockOrgIdfname,FStockDeptId.fnumber as FStockDeptIdfnumber,FStockDeptId.fname as FStockDeptIdfname,FStockId.fnumber as FStockIdfnumber,FStockId.fname as FStockIdfname,FApproveDate";
        logger.info("fieldKeys---->{}",fieldKeys);
        KingdeeRequest reqeust=new KingdeeRequest("DE_SCMS_ALLOTRECEIPT",fieldKeys ,filterString.toString(),rowNum,1000);
        List<KingdeeRequest> parameters=new ArrayList<>();
        parameters.add(reqeust);
        BaseRequest baseRequest=new BaseRequest(parameters);
        Gson gson = new Gson();
        String jsonString = gson.toJson(baseRequest);
        System.out.println(jsonString);
        HashMap<String,String> map=new HashMap<>();
        map.put("kdservice-sessionid",session);
        String response= OkhttpUtil.post(queryUrl,jsonString,map);
        System.out.println("response------>"+response);
        if(response.contains("ErrorCode"))
        {
            ErrorInfo errorInfo=  getErrorInfo(response,"postQueryKingdeeMaterialPurchase--approveDate--"+approveDate);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else if(response.contains("response_error"))
        {
            ErrorInfo errorInfo=  new ErrorInfo(1,"10001","postQueryKingdeeMaterialPurchase--approveDate--"+approveDate+"--response---"+response);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else
        {
            List<MaterialPurchaseResponse> orgs = gson.fromJson(response, new TypeToken<List<MaterialPurchaseResponse>>(){}.getType());
            commonResponse.setFlag(0);
            commonResponse.setData(orgs);
        }

        return commonResponse;
    }




    /**
     * 查询分步式调出单
     * request body
     {
     "parameters": [
     {
     "FormId": "STK_TRANSFEROUT",
     "FieldKeys": "fbillno,FMaterialId,FLot,FQty,FUnitID.fnumber as FUnitIDfnumber,FUnitID.fname as FUnitIDfname,FExtAuxUnitId.fnumber as FExtAuxUnitIdfnumber,FExtAuxUnitId.fname as FExtAuxUnitIdfname,FExtAuxUnitQty,FMaterialId.Fspecification as FMaterialIdFspecification,FNegotiatePrice,FNegotiateAmount,FDate,FStockOrgID.fnumber as FStockOrgIDfnumber,FStockOrgID.fname as FStockOrgIDfname,FStockInOrgID.fnumber as FStockInOrgIDfnumber,FStockInOrgID.fname as FStockInOrgIDfname,FINDEPTID.fnumber as FINDEPTIDfnumber,FINDEPTID.fname as FINDEPTIDfname,FOUTDEPTID.fnumber as FOUTDEPTIDfnumber,FOUTDEPTID.fname as FOUTDEPTIDfname,FApproveDate",
     "FilterString": "FDocumentStatus='C'  and FApproveDate>'2024-01-01'",
     "StartRow": 0,
     "Limit": 100
     }
     ]
     }
     * @param session
     * @param approveDate
     * @param pageNum
     * @return
     *   "FilterString": "FDocumentStatus='C' AND FMaterialId.fnumber LIKE '1%' and FApproveDate>'2023-01-15'
     *   and FOUTDEPTID.fnumber is not null and FStockOrgID.fnumber in ('BU101006')",
     */
    public static CommonResponse<List<MaterialTransferoutResponse>> postQueryKingdeeMaterialTransferout(String session, String approveDate, int rowNum,List<String> depts) {

        CommonResponse<List<MaterialTransferoutResponse>> commonResponse=new CommonResponse();
        StringBuffer filterString =new StringBuffer("FDocumentStatus='C' AND FMaterialId.fnumber LIKE '1%'  and FOUTDEPTID.fnumber is not null ");
        if(StringUtils.isNotEmpty(approveDate)) {
//            filterString.append(" and FApproveDate>'"+approveDate+"'");

            LocalDate today = LocalDate.parse(approveDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDate lastDay = today.with(TemporalAdjusters.lastDayOfMonth());
            filterString.append(" and FDate>='"+approveDate+"'and FDate<='"+lastDay+"' ");
        }
        if(!CollectionUtils.isEmpty(depts))
            filterString.append(" and FStockOrgId.fnumber in("+ CommonUtil.getStringDepts1(depts)+")");
        System.out.println("filterString---->"+filterString);
        String queryFields="FID,FSTKTRSOUTENTRY_FEntryId as FDID,'-1' as flag,fbillno,FMaterialId,FMaterialId.fnumber as FMaterialIdfnumber ,FMaterialId.fname as FMaterialIdfname,FLot,FQty,FUnitID.fnumber as FUnitIDfnumber,FUnitID.fname as FUnitIDfname,FExtAuxUnitId.fnumber as FExtAuxUnitIdfnumber,FExtAuxUnitId.fname as FExtAuxUnitIdfname,FExtAuxUnitQty,FMaterialId.Fspecification as FMaterialIdFspecification,FNegotiatePrice,FNegotiateAmount,FDate,FStockOrgID.fnumber as FStockOrgIDfnumber,FStockOrgID.fname as FStockOrgIDfname,FStockInOrgID.fnumber as FStockInOrgIDfnumber,FStockInOrgID.fname as FStockInOrgIDfname,FINDEPTID.fnumber as FINDEPTIDfnumber,FINDEPTID.fname as FINDEPTIDfname,FOUTDEPTID.fnumber as FOUTDEPTIDfnumber,FOUTDEPTID.fname as FOUTDEPTIDfname,FApproveDate,FSrcBillNo";
        KingdeeRequest reqeust=new KingdeeRequest("STK_TRANSFEROUT",
                queryFields,filterString.toString(),rowNum,1000);
        List<KingdeeRequest> parameters=new ArrayList<>();
        parameters.add(reqeust);
        BaseRequest baseRequest=new BaseRequest(parameters);
        Gson gson = new Gson();
        String jsonString = gson.toJson(baseRequest);
        System.out.println(jsonString);
        HashMap<String,String> map=new HashMap<>();
        map.put("kdservice-sessionid",session);
        String response= OkhttpUtil.post(queryUrl,jsonString,map);
        System.out.println("response------>"+response);
        if(response.contains("ErrorCode"))
        {
            ErrorInfo errorInfo=  getErrorInfo(response,"postQueryKingdeeMaterialTransferout--approveDate--"+approveDate);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else if(response.contains("response_error"))
        {
            ErrorInfo errorInfo=  new ErrorInfo(1,"10001","postQueryKingdeeMaterialTransferout--approveDate--"+approveDate+"--response---"+response);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else
        {
            List<MaterialTransferoutResponse> orgs = gson.fromJson(response, new TypeToken<List<MaterialTransferoutResponse>>(){}.getType());
            commonResponse.setFlag(0);
            commonResponse.setData(orgs);
        }

        return commonResponse;

    }

    /**
     * 查询分步式调入单
     *      * request body
     {
     "parameters": [
     {
     "FormId": "STK_TRANSFERIN",
     "FieldKeys": "fbillno,FMaterialId,FLot,FQty,FUnitID.fnumber as FUnitIDfnumber,FUnitID.fname as FUnitIDfname,FExtAuxUnitId.fnumber as FExtAuxUnitIdfnumber,FExtAuxUnitId.fname as FExtAuxUnitIdfname,FExtAuxUnitQty,FMaterialId.Fspecification as FMaterialIdFspecification,FNegotiatePrice,FNegotiateAmount,FPlanTransferQty,FDate,FStockOrgID.fnumber as FStockOrgIDfnumber,FStockOrgID.fname as FStockOrgIDfname,FStockOutOrgID.fnumber as FStockOutOrgIDfnumber,FStockOutOrgID.fname as FStockOutOrgIDfname,FINDEPTID.fnumber as FINDEPTIDfnumber,FINDEPTID.fname as FINDEPTIDfname,FOUTDEPTID.fnumber as FOUTDEPTIDfnumber,FOUTDEPTID.fname as FOUTDEPTIDfname,FSrcBillNo,FApproveDate",
     "FilterString": "FDocumentStatus='C' ",
     "StartRow": 0,
     "Limit": 100
     }
     ]
     }
     * @param session
     * @param approveDate
     * @param pageNum
     * @return
     *     //过滤条件
     *
     *         /**
     *          * FDocumentStatus='C' 审核通过
     *          * FMaterialId.fnumber LIKE '1%'  是厨部使用的原材料
     *          * FApproveDate 审核时间
     *          * FINDEPTID.fnumber is not null 调入工作组不可以为空，否则无法统计，没有意义
     *          * FStockOrgID.fnumber in('BU1010010013') 必须是开通本系统的门店
     *          *     "FilterString": "FDocumentStatus='C' AND FMaterialId.fnumber LIKE '1%'
     *          *     and FApproveDate>'2024-01-15'
     *          *     and FINDEPTID.fnumber is not null and FStockOrgID.fnumber in('BU1010010013')",
     *          */

    public static CommonResponse<List<MaterialTransferoutResponse>> postQueryKingdeeMaterialTransferin(String session, String approveDate, int rowNum,List<String> depts) {
        CommonResponse<List<MaterialTransferoutResponse>> commonResponse=new CommonResponse();
        StringBuffer filterString =new StringBuffer("FDocumentStatus='C'  and FINDEPTID.fnumber is not null");
        if(StringUtils.isNotEmpty(approveDate))
            filterString.append(" and FApproveDate>'"+approveDate+"'");
        if(!CollectionUtils.isEmpty(depts))
            filterString.append(" and FStockOrgId.fnumber in("+ CommonUtil.getStringDepts1(depts)+")");
        System.out.println("filterString---->"+filterString);
        String queryFields= "FID,FSTKTRSINENTRY_FEntryId AS FDID,'1' as flag,fbillno,FMaterialId,FMaterialId.fnumber as FMaterialIdfnumber ,FMaterialId.fname as FMaterialIdfname,FLot,FQty,FUnitID.fnumber as FUnitIDfnumber,FUnitID.fname as FUnitIDfname,FExtAuxUnitId.fnumber as FExtAuxUnitIdfnumber,FExtAuxUnitId.fname as FExtAuxUnitIdfname,FExtAuxUnitQty,FMaterialId.Fspecification as FMaterialIdFspecification,FNegotiatePrice,FNegotiateAmount,FPlanTransferQty,FDate,FStockOrgID.fnumber as FStockOrgIDfnumber,FStockOrgID.fname as FStockOrgIDfname,FStockOutOrgID.fnumber as FStockOutOrgIDfnumber,FStockOutOrgID.fname as FStockOutOrgIDfname,FINDEPTID.fnumber as FINDEPTIDfnumber,FINDEPTID.fname as FINDEPTIDfname,FOUTDEPTID.fnumber as FOUTDEPTIDfnumber,FOUTDEPTID.fname as FOUTDEPTIDfname,FSrcBillNo,FApproveDate";
        KingdeeRequest reqeust=new KingdeeRequest("STK_TRANSFERIN",
                queryFields,filterString.toString(),rowNum,1000);
        List<KingdeeRequest> parameters=new ArrayList<>();
        parameters.add(reqeust);
        BaseRequest baseRequest=new BaseRequest(parameters);
        Gson gson = new Gson();
        String jsonString = gson.toJson(baseRequest);
        System.out.println(jsonString);
        HashMap<String,String> map=new HashMap<>();
        map.put("kdservice-sessionid",session);
        String response= OkhttpUtil.post(queryUrl,jsonString,map);
        System.out.println("response------>"+response);
        if(response.contains("ErrorCode"))
        {
            ErrorInfo errorInfo=  getErrorInfo(response,"postQueryKingdeeMaterialTransferin--approveDate--"+approveDate);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else if(response.contains("response_error"))
        {
            ErrorInfo errorInfo=  new ErrorInfo(1,"10001","postQueryKingdeeMaterialTransferin--approveDate--"+approveDate+"--response---"+response);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else
        {
            if(!"[]".equals(response)) {
                List<MaterialTransferoutResponse> list = gson.fromJson(response, new TypeToken<List<MaterialTransferoutResponse>>() {
                }.getType());
                commonResponse.setFlag(0);
                commonResponse.setData(list);
            }
        }

        return commonResponse;

    }

    public static CommonResponse<List<com.ruoyi.system.api.domain.EmpResponse>> postQueryKingdeeEmp(String session, String approveDate, int rowNum,String FStaffNumber) {
        CommonResponse<List<com.ruoyi.system.api.domain.EmpResponse>> commonResponse=new CommonResponse();

        StringBuffer filterString =new StringBuffer("FDocumentStatus='C'");
        if(StringUtils.isNotEmpty(approveDate))
            filterString.append(" and FAuditDate>'"+approveDate+"'");
        if(StringUtils.isNotEmpty(FStaffNumber))
            filterString.append(" and FStaffNumber='"+FStaffNumber+"'");

        System.out.println("filterString---->"+filterString);
        String queryFields= "FID,FNumber,FStaffNumber,fname,FMobile,FEmail,F_WGNV_Text,FForbidStatus,FUseOrgId.fnumber as FUseOrgIdfnumber,FUseOrgId.fname as FUseOrgIdfname,FAuditDate";
        KingdeeRequest reqeust=new KingdeeRequest("BD_Empinfo",
                queryFields,filterString.toString(),rowNum,1000);
        List<KingdeeRequest> parameters=new ArrayList<>();
        parameters.add(reqeust);
        BaseRequest baseRequest=new BaseRequest(parameters);
        Gson gson = new Gson();
        String jsonString = gson.toJson(baseRequest);
        System.out.println(jsonString);
        HashMap<String,String> map=new HashMap<>();
        map.put("kdservice-sessionid",session);
        String response= OkhttpUtil.post(queryUrl,jsonString,map);
        System.out.println("response------>"+response);
        if(response.contains("ErrorCode"))
        {
            ErrorInfo errorInfo=  getErrorInfo(response,"postQueryKingdeeEmp--approveDate--"+approveDate);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else if(response.contains("response_error"))
        {
            ErrorInfo errorInfo=  new ErrorInfo(1,"10001","postQueryKingdeeEmp--approveDate--"+approveDate+"--response---"+response);
            commonResponse.setFlag(1);
            commonResponse.setErrorInfo(errorInfo);
        }
        else
        {
            List<com.ruoyi.system.api.domain.EmpResponse> orgs = gson.fromJson(response, new TypeToken<List<com.ruoyi.system.api.domain.EmpResponse>>(){}.getType());
            commonResponse.setFlag(0);
            commonResponse.setData(orgs);
        }

        return commonResponse;


    }


    public static void main(String[] args) {

//
//        String session=logonKingdeeK3Cloud();
//        System.out.println(session);
        String session1="57e09c22-a909-4226-ac12-030dbaa01d1c";
//        CommonResponse<List<MaterialTransferinResponse>> list= postQueryKingdeeMaterialTransferin( session, "2023-01-01",0);
//        System.out.println(list);
//        CommonResponse<List<MaterialTransferoutResponse>> list= postQueryKingdeeMaterialTransferout( session, "2023-01-01",0);
//        System.out.println(list);
//      CommonResponse<List<EmpResponse>> list= postQueryKingdeeEmp( session, "2023-01-01",0);
//        System.out.println(list);
 /*部门查询*/
//        CommonResponse<List<OrgResponse>> list2= postQueryKingdeeDept(session1, "BU1010010022","2023-03-01");
//        System.out.println(list2);


        postQueryKingdeeMaterialTransUnit( session1, "2023-01-01",0);
    }



}
